package com.zrrd.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zrrd.model.product.*;
import com.zrrd.product.mapper.*;
import com.zrrd.product.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private BaseCategory1Mapper category1Mapper;
    @Autowired
    private BaseCategory2Mapper category2Mapper;
    @Autowired
    private BaseCategory3Mapper category3Mapper;
    @Autowired
    private BaseAttrInfoMapper attrInfoMapper;
    @Autowired
    private BaseAttrValueMapper attrValueMapper;
    @Autowired
    private  BaseSaleAttrMapper baseSaleAttrMapper;

    @Override
    public List<BaseCategory1> getCategory1() {
        return category1Mapper.selectList(null);
    }

    @Override
    public List<BaseCategory2> getCategory2(Long category1_id) {
        return category2Mapper.selectList(new QueryWrapper<BaseCategory2>().
                eq("category1_id", category1_id));
    }

    @Override
    public List<BaseCategory3> getCategory3(Long category2_id) {
        return category3Mapper.selectList(new QueryWrapper<BaseCategory3>().
                eq("category2_id", category2_id));
    }


    @Override
    public List<BaseAttrInfo> getBaseAttrInfo(Long category1Id, Long category2Id, Long category3Id) {
        return attrInfoMapper.getBaseAttrInfo(category1Id, category2Id, category3Id);
    }

    @Override
    @Transactional
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //判断是新增还是修改
        if (baseAttrInfo.getId() == null) {
            //给平台属性表添加数据
            attrInfoMapper.insert(baseAttrInfo);
        } else {
            //修改平台属性表数据
            attrInfoMapper.updateById(baseAttrInfo);
            //删除原本关联的属性值列表
            QueryWrapper<BaseAttrValue> wrapper = new QueryWrapper<>();
            wrapper.eq("attr_id", baseAttrInfo.getId());
            attrValueMapper.delete(wrapper);
        }
        //获取参数中属性值的集合
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        //遍历集合
        for (BaseAttrValue baseAttrValue : attrValueList) {
            //给当前属性值设置关联的属性id
            baseAttrValue.setAttrId(baseAttrInfo.getId());
            //给平台属性对应的属性值添加数据
            attrValueMapper.insert(baseAttrValue);
        }

    }

    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        QueryWrapper<BaseAttrValue> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_id", attrId);
        return attrValueMapper.selectList(wrapper);
    }

    @Override
    public List<BaseSaleAttr> getBaseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }
}
